package thoven.achievement.net.jsonutil.intention

import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import thoven.achievement.net.jsonutil.service.JsonCleaner

/**
 * 解转义 JSON 的意图操作
 */
class UnescapeJsonIntention : PsiElementBaseIntentionAction(), IntentionAction {
    
    override fun getText(): String = "解转义 JSON"
    
    override fun getFamilyName(): String = "JSON Utilities"
    
    override fun isAvailable(project: Project, editor: Editor?, element: PsiElement): Boolean {
        if (editor == null) return false
        
        val selectionModel = editor.selectionModel
        if (!selectionModel.hasSelection()) return false
        
        val selectedText = selectionModel.selectedText ?: return false
        
        // 检测是否包含转义字符
        return selectedText.contains("\\\"") || selectedText.contains("\\\\")
    }
    
    override fun invoke(project: Project, editor: Editor?, element: PsiElement) {
        if (editor == null) return
        
        val selectionModel = editor.selectionModel
        val selectedText = selectionModel.selectedText ?: return
        
        val unescaped = JsonCleaner.unescapeJson(selectedText)
        
        WriteCommandAction.runWriteCommandAction(project) {
            editor.document.replaceString(
                selectionModel.selectionStart,
                selectionModel.selectionEnd,
                unescaped
            )
        }
    }
}

